/**
 * 
 */
package net.toocruel.iqismart.security.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.toocruel.iqismart.security.browser.dto.UsernameLoginError;
import net.toocruel.iqismart.security.core.exception.MyUsernameNotFoundException;
import net.toocruel.iqismart.security.core.properties.SecurityProperties;
import net.toocruel.iqismart.security.core.support.Result;
import net.toocruel.iqismart.security.core.validate.code.ValidateCodeException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 浏览器环境下登录失败的处理器
 * 
 * @author toocruel
 *
 */
@Component("tipaskAuthenctiationFailureHandler")
public class TipaskAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ObjectMapper objectMapper;
	
	@Autowired
	private SecurityProperties securityProperties;

	private RequestCache requestCache = new HttpSessionRequestCache();
	
	/* (non-Javadoc)
	 * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
	 */
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		
		logger.info("登录失败");
		
		if (StringUtils.isBlank(request.getHeader("referer"))) {
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(objectMapper.writeValueAsString(new Result(-1,exception.getMessage())));
		}else{
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String imageCode = request.getParameter("imageCode");
			UsernameLoginError usernameLoginError = new UsernameLoginError();
			usernameLoginError.setUsername(username);
			usernameLoginError.setPassword(password);
			usernameLoginError.setImageCode(imageCode);
			if(exception instanceof ValidateCodeException){
				//验证码相关异常
				usernameLoginError.setValidateCodeMsg("验证码错误");
			}else if(exception.getCause() instanceof  MyUsernameNotFoundException){
				//用户不存在
				usernameLoginError.setUsernameMsg(exception.getMessage());
			}else if(exception instanceof BadCredentialsException){
				//密码不正确
				usernameLoginError.setPasswordMsg("密码不正确");
			}else if(exception instanceof AccountExpiredException){
				//账号过期
				usernameLoginError.setUsernameMsg("账号已过期");
			}else if(exception instanceof LockedException){
				//账号锁定
				usernameLoginError.setUsernameMsg("账号被锁定");
			}else if(exception instanceof DisabledException){
				//账号不可用
				usernameLoginError.setUsernameMsg("账号未启用");
			}else if(exception instanceof SessionAuthenticationException){
				//并发登录
				usernameLoginError.setUsernameMsg("因在其他地方登录，被强制下线");
			}
			request.getSession().setAttribute("usernameLoginError",usernameLoginError);

			String referer = request.getHeader("referer");
			if(referer.contains("/admin")){
				response.sendRedirect(securityProperties.getBrowser().getSingInFailedUrlAdmin());
			}else{
				if(StringUtils.isNotBlank(request.getParameter("return"))){
					response.sendRedirect(securityProperties.getBrowser().getSingInFailedUrl()+"?return="+request.getParameter("return"));
				}else{
					response.sendRedirect(securityProperties.getBrowser().getSingInFailedUrl());
				}
			}
//			SavedRequest savedRequest = requestCache.getRequest(request, response);
//			if(savedRequest !=null ){
//				String targetUrl = savedRequest.getRedirectUrl();
//				if(targetUrl.contains("/admin")){
//					response.sendRedirect(securityProperties.getBrowser().getSingInFailedUrlAdmin());
//				}else{
//					response.sendRedirect(securityProperties.getBrowser().getSingInFailedUrl());
//				}
//			}else{
//				response.sendRedirect(securityProperties.getBrowser().getSignInPage());
//			}

//			super.onAuthenticationFailure(request, response, exception);
		}
		
	}
}
